const express  = require('express');
const cors  = require('cors');
const {parse} = require('muninn');
const { buildExcel, excelKayReg, request } = require('./base.js');
const axios  = require('axios');

const path = require('path');
const fs  = require('fs');


// 引入函数
const api = require('./api/index.js');
const {config} = require('./domtree.js');

const template = `<style>li {margin-bottom: 1rem;}ul li {list-style-type: none;}</style>
                  <h1 style='text-align:center;font-size: 1.6rem;'>FC数据API</h1>
                  <ul>
                      <li>
                          <h4 style="margin:0 0 0.4rem;">获取实时结果：</h4>
                          <div>接口地址：<a href="/findDrawNotice">/findDrawNotice</a></div>
                      </li>
                      <li>
                          <h4 style="margin:0 0 0.4rem;">获取历史记录：</h4>
                          <div>接口地址：<a href="/findHistory?lotid=7xc&limit=10&year=">/findHistory</a></div>
                      </li>
                      <li>
                          <h4 style="margin:0 0 0.4rem;">获取历史详情：</h4>
                          <div>接口地址：<a href="/findDetail?lotid=dlt&issue=2024090&isone=0">/findDetail</a></div>
                      </li>
                      <li>
                          <h4 style="margin:0 0 0.4rem;">查询走势数据：</h4>
                          <div>接口地址：<a href="/findTrend?type=klb&limit=2">/findTrend</a></div>
                      </li>
                      <li>
                          <h4 style="margin:0 0 0.4rem;">查询历史遗漏：</h4>
                          <div>接口地址：<a href="/findOmission?type=klb&value=1,7,8">/findOmission</a></div>
                      </li>
                  </ul>`;
const app = express()
app.use(cors());
app.use('/files', express.static('files'))
app.use(express.json());
app.use(express.urlencoded({ extended: true }));



app.get('/', async (req, res) => {
    res.setHeader('Content-Type', "text/html;charset=utf-8");
    res.write(template);
    res.end();
});


app.get('/historyExcel', async (req, res) => {
    let {lotid, limit, year, type} = req.query;
    let typearr = ['html','do'];  // html页面、excel表格
    let reqtype = type && typearr.find(val=>{return val == type.toLowerCase()}) ? type : 'html';
    if(!lotid || !config.types.find(val=>{return val.toLowerCase() == lotid.toLowerCase()}) ) {lotid = '3d';}
    const domLog = await api.historyExcel(lotid, limit, year);
    console.log(domLog.data)
    if(reqtype == 'html') {
      res.setHeader('Content-Type', "text/html;charset=utf-8");
      res.write(domLog.data);
    } else {
      const data = parse(domLog.data, config.log['t'+lotid.toLowerCase()]);
      const list = [...data.filter(item => item.qihao != null)];
      let options = [
          {
              "name": "sheet1",
              "title": `${lotid} ${list[list.length-1].riqi} - ${list[0].riqi} 共${list.length}数据`,
              "data": [
                  excelKayReg.map(itm=>itm.name),
              ]
          }
      ]
      
      list.map(item=>{
        options[0].data.push(excelKayReg.map(itm=>String(item[itm.key])))
      })
      const filePath = await buildExcel(options);
      const fileName = path.basename(filePath);
      try {
        res.download(filePath, fileName, (err) => {
            if (err) {
                console.log(err, "文件下载失败");
                res.status(500).send('文件下载失败');
            } else {
                fs.unlinkSync(filePath); // 下载完成后删除文件
            }
        });
      } catch (error) {
          console.log(err, "导出excel失败");
          res.status(500).send('导出excel失败');
      }
    }
});


app.get('/findTrend', async (req, res) => {
  let {type,limit} = req.query;
  const omission = await api.findTrend(type,limit);
  console.log(omission.data)
  res.send({
    errcode: 200,
    data: omission.data
  });
});


app.get('/findOmission', async (req, res) => {
  let {type,value} = req.query;
  const omission = await api.findOmission(type,value);
  console.log(omission.data)
  res.send({
    errcode: 200,
    data: omission.data
  });
});

app.get('/findBaseOmission', async (req, res) => {
  const omission = await api.findBaseOmission();
  res.send({
    errcode: 200,
    data: omission.data
  });
});

// 详情
app.get('/findDetail', async (req, res) => {
  let {lotid, issue, isone} = req.query;
  if(!lotid || !config.types.find(val=>{return val.toLowerCase() == lotid.toLowerCase()}) ) {lotid = '3d';}
  const domDetail = await api.findDetail(lotid, issue, isone);
  console.log(domDetail.data)
  if(!domDetail.data) {
      res.send({
        errcode: 201,
        data: null
      });
      return
  }
  let data = parse(domDetail.data, config.detail['t'+lotid.toLowerCase()]);
  
  console.log(data.data)
  
  if(lotid == 'kl8') {
    data.data = data.data.reduce((acc, obj) => {
      const groupKey = obj.xuan;
      if (!acc[groupKey]) {
        acc[groupKey] = [];
      }
      acc[groupKey].push(obj);
      return acc;
    }, {});
    for(let key in data.data) {
      data.data[key] = data.data[key].filter(item => item.jiangjin != null)
    }
  } else {
    data.data = data.data.filter(item => item.jiangjin != null)
  }
  res.send({
    errcode: 200,
    type: lotid,
    qihao: issue,
    data: data
  });
});

// 公告
app.get('/findDrawNotice', async (req, res) => {
    
  const list = await api.findDrawNotice();
  res.send({
    errcode: 200,
    data: list.data
  });
  setFunInc();
});

// 历史
app.get('/findHistory', async (req, res) => {
  let {lotid, limit, year} = req.query;
  if(!lotid || !config.types.find(val=>{return val.toLowerCase() == lotid.toLowerCase()}) ) {lotid = '3d';}
  const domLog = await api.findHistory(lotid, limit, year);
  console.log(domLog.data)

  const data = parse(domLog.data, config.log['t'+lotid.toLowerCase()]);
  // console.log(data)
  const list = [...data.filter(item => item.qihao != null)];
  res.send({
    errcode: 200,
    type: lotid,
    data: list
  });
});
function setFunInc() {
    request({
        url: `https://v2.huanghaibo.online/api/leap/setFunInc`,
        headers: {
            "content-type": "application/json;charset:utf-8",
        },
        method: "GET"
    });
}
app.listen(12345, () => {
  console.log("服务器启动成功")
})
